package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.springframework.stereotype.Repository;

import com.fsd.core.common.BusinessException;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.F_flownode;
import com.fsd.admin.service.F_flownodeService;
import com.fsd.admin.dao.F_flownodeDao;
import com.google.gson.Gson;

@Repository("f_flownodeServiceImpl")
public class F_flownodeServiceImpl extends MainServiceImpl<F_flownode, String> implements F_flownodeService{

	//流程节点类型 f_fnjdlx
	/**
	 * 开始节点
	 */
	public static final String fnksd = "f_fnksd";
	/**
	 * 自动审批节点，根据节点预先设定的值进行自动比较，或者调用接口进行数据比较，根据比较结果分别自动进入不同的下一节点，自动节点两个结果，True节点，False节点。
	 */
	public static final String fnzdp = "f_fnzdp";
	/**
	 * 自动选择(单)节点，上一节点审批完成时，提取自动选择节点条件数据，只能选择其中一个条件，调用系统接口，按预先设定好的程序判断自动进入下一节点，自动节点两个结果，True节点，False节点。
	 */
	public static final String fnzxy = "f_fnzxy";
	/**
	 * 自动选择(多)节点，上一节点审批完成时，提取自动选择节点条件数据，可以选择多个条件，调用系统接口，按预先设定好的程序判断自动进入下一节点，自动节点两个结果，True节点，False节点。
	 */
	public static final String fnzxd = "f_fnzxd";
	/**
	 * 部门审批节点，当前节点设定部门ID，根据登录人为设定部门人员则可进行提取节点进行审核，审核完成后进入下一节点。
	 */
	public static final String fnbmp = "f_fnbmp";
	/**
	 * 单人审批节点，单人一人审批节点，条件只能设定为一人。
	 */
	public static final String fndrp = "f_fndrp";
	/**
	 * 多人审批(并)节点，当前节点下的预设的所有人，都必须进行审批，一票否决制，按照否决操作进行节点流程处理，进入下一节点需全票通过。
	 */
	public static final String fndrb = "f_fndrb";
	/**
	 * 多人审批(或)节点，当前节点下的预设的所有人，都可以看到进入此节点数据，都可以进行审批，只要有一人审批通过，节点操作就完成进入下一节点。
	 */
	public static final String fndrh = "f_fndrh";
	/**
	 * 选择审批节点，当前节点下的预设多名审批人，上一节点审批完成时，提取选择审批节点条件数据，进行选择其中一个条件，确定当前节点的处理人。
	 */
	public static final String fnxzp = "f_fnxzp";
	/**
	 * 结束节点，FSDFLOWNODEEND
	 */
	public static final String fnjsd = "f_fnjsd";
	
    private static final Logger log = Logger.getLogger(F_flownodeServiceImpl.class);
    private String depict = "流程节点";
    
    @Resource(name = "f_flownodeDaoImpl")
	public void setBaseDao(F_flownodeDao f_flownodeDao) {
		super.setBaseDao(f_flownodeDao);
	}
	
	@Resource(name = "f_flownodeDaoImpl")
	private F_flownodeDao objectDao;
	

	/**
	 * 根据数据对象ID加载对象
	 * @param previousID
	 * @return
	 * @throws Exception
	 */
	public F_flownode getObjectByPreviousID(String previousID)  throws Exception{
		String sql = "from F_flownode t where previousid = '" + previousID + "'";
		List<F_flownode> objList = objectDao.queryByHql(sql);
		if (objList != null && objList.size() > 0){
			return objList.get(0);
		}
		return null;
	}
	
	/**
	 * 根据节点集合排列成流程列表
	 */
	private List<F_flownode> getSortObjectList(List<F_flownode> list, String projectid, boolean isProject){
		List<F_flownode> objList = new ArrayList<F_flownode>();
		if (isProject){
			F_flownode fn = new F_flownode();
			fn.setId(projectid);
			fn.setName("流程开始");
			fn.setNodetype(fnksd);
			fn.setNodetypename("开始节点");
			objList.add(fn);
		}
		if (list == null || list.size() == 0)
			return objList;
		List<F_flownode> tempList = new ArrayList<F_flownode>();
		for (F_flownode obj : list) {
			tempList.add(obj);
		}
		List<String> ids = new ArrayList<String>();
		List<String> idList = new ArrayList<String>();
		idList.add(projectid);
		boolean isTrue = false;
		do {
			isTrue = false;
			ids.clear();
			for (String id : idList) {
				ids.add(id);
			}
			idList.clear();
			for (F_flownode obj : list) {
				for (String id : ids) {
					if (obj.getPreviousid().equals(id)){
						idList.add(obj.getId());
						objList.add(obj);
						tempList.remove(obj);
						isTrue = true;
					}
				}
			}
		} while (isTrue);
		for (F_flownode obj : tempList) {
			objList.add(obj);
		}
		return objList;
	}
	
	/**
	 * 根据项目ID加载数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public List<F_flownode> getObjectListByProjectID(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		String projectid = "";
		boolean isProject = false;
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("projectid") != null && !"".equals(objectMap.get("projectid"))){
				projectid = objectMap.get("projectid").toString();
				c.add(Restrictions.eq("projectid", projectid));
			}
			if(objectMap.get("isproject") != null && !"".equals(objectMap.get("isproject"))){
				if ("true".equals(objectMap.get("isproject").toString())){
					isProject = true;
				}
			}
		}
		return  this.getSortObjectList(objectDao.getList(c), projectid, isProject);
	}

    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	public void save(F_flownode obj, A_Employee employee) throws Exception{
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
        	F_flownode old_obj = objectDao.get(obj.getId());
        	old_obj.setName(obj.getName());
        	old_obj.setNodetype(obj.getNodetype());
        	old_obj.setNodetypename(obj.getNodetypename());
        	old_obj.setCode(obj.getCode());
        	old_obj.setName(obj.getName());
        	old_obj.setPreviousid(obj.getPreviousid());
        	old_obj.setPreviousname(obj.getPreviousname());
        	old_obj.setNextid(obj.getNextid());
        	old_obj.setNextname(obj.getNextname());
        	old_obj.setNexttype(obj.getNexttype());
        	old_obj.setNexttypename(obj.getNexttypename());
        	old_obj.setFalseid(obj.getFalseid());
        	old_obj.setFalsename(obj.getFalsename());
        	old_obj.setIsdeliver(obj.getIsdeliver());
        	if (!"true".equals(old_obj.getIsdeliver())){
        		old_obj.setIsdeliver("false");
			}
        	old_obj.setIsextract(obj.getIsextract());
        	if (!"true".equals(old_obj.getIsextract())){
        		old_obj.setIsextract("false");
			}
        	old_obj.setIsrefusal(obj.getIsrefusal());
        	if (!"true".equals(old_obj.getIsrefusal())){
        		old_obj.setIsrefusal("false");
			}
        	old_obj.setIsreturn(obj.getIsreturn());
        	if (!"true".equals(old_obj.getIsreturn())){
        		old_obj.setIsreturn("false");
			}
        	old_obj.setUpdatedate(this.getData());//设置修改日期
        	old_obj.setUpdateemployeeid(employee.getId());//设置修改用户id
        	old_obj.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
            objectDao.update(old_obj);
        }else{
            //添加
            obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
        	if (!"true".equals(obj.getIsdeliver())){
        		obj.setIsdeliver("false");
			}
        	if (!"true".equals(obj.getIsextract())){
        		obj.setIsextract("false");
			}
        	if (!"true".equals(obj.getIsrefusal())){
        		obj.setIsrefusal("false");
			}
        	if (!"true".equals(obj.getIsreturn())){
        		obj.setIsreturn("false");
			}
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			objectDao.save(obj);
        }
        this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, F_flownodeServiceImpl.class);
	}
    
    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update F_flownode t set t.deleted = '1', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPESC, this.depict + ids, employee, F_flownodeServiceImpl.class);
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public F_flownode getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		F_flownode obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
}
